use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::borrow::Borrow;
use std::cell::UnsafeCell;
use std::collections::hash_map::{
    IntoIter as MapIntoIter, Iter as MapIter, IterMut as MapIterMut, Keys, Values, ValuesMut,
};
use std::collections::HashMap;
use std::fmt::{Debug, Formatter};
use std::hash::Hash;
use std::ops::{Deref, DerefMut};
use std::sync::{Arc, RwLock, RwLockWriteGuard};

/// 同步哈希映射，支持多读少写的场景
/// this sync map used to many reader, writer less. space-for-time strategy
pub struct SyncHashMap<K, V> {
    /// 底层数据存储，使用UnsafeCell避免锁开销
    dirty: UnsafeCell<HashMap<K, V>>,
    /// 读写锁，用于保护并发访问
    lock: RwLock<()>,
}

/// 标记为Send，因为使用了UnsafeCell但有锁保护
/// this is safety, dirty mutex ensure
unsafe impl<K, V> Send for SyncHashMap<K, V> {}

/// 标记为Sync，因为使用了UnsafeCell但有锁保护
/// this is safety, dirty mutex ensure
unsafe impl<K, V> Sync for SyncHashMap<K, V> {}

/// 索引操作，无锁访问（unsafe但在单线程场景下高效）
impl<K, V> std::ops::Index<&K> for SyncHashMap<K, V>
where
    K: Eq + Hash,
{
    type Output = V;

    fn index(&self, index: &K) -> &Self::Output {
        unsafe { &(&*self.dirty.get())[index] }
    }
}

impl<K, V> SyncHashMap<K, V>
where
    K: Eq + Hash,
{
    /// 创建一个新的Arc包装的SyncHashMap
    pub fn new_arc() -> Arc<Self> {
        Arc::new(Self::new())
    }

    /// 创建一个新的空映射
    pub fn new() -> Self {
        Self {
            dirty: UnsafeCell::new(HashMap::new()),
            lock: RwLock::new(()),
        }
    }

    /// 使用指定容量创建一个新的映射
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            dirty: UnsafeCell::new(HashMap::with_capacity(capacity)),
            lock: RwLock::new(()),
        }
    }

    /// 使用现有的HashMap创建一个同步映射
    pub const fn with_map(map: HashMap<K, V>) -> Self {
        Self {
            dirty: UnsafeCell::new(map),
            lock: RwLock::new(()),
        }
    }

    /// 插入键值对，使用写锁保护
    #[inline(always)]
    pub fn insert(&self, k: K, v: V) -> Option<V> {
        let _lock = self.lock.write();
        let m = unsafe { &mut *self.dirty.get() };
        m.insert(k, v)
    }

    /// 可变引用下的插入操作，无锁保护（调用者需确保线程安全）
    #[inline(always)]
    pub fn insert_mut(&mut self, k: K, v: V) -> Option<V> {
        let m = unsafe { &mut *self.dirty.get() };
        m.insert(k, v)
    }

    /// 移除键值对，使用写锁保护
    #[inline(always)]
    pub fn remove(&self, k: &K) -> Option<V> {
        let _lock = self.lock.write();
        let m = unsafe { &mut *self.dirty.get() };
        m.remove(k)
    }

    /// 可变引用下的移除操作，无锁保护（调用者需确保线程安全）
    #[inline(always)]
    pub fn remove_mut(&mut self, k: &K) -> Option<V> {
        let m = unsafe { &mut *self.dirty.get() };
        m.remove(k)
    }

    /// 获取映射长度，使用读锁保护
    #[inline(always)]
    pub fn len(&self) -> usize {
        let _lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        m.len()
    }

    /// 判断映射是否为空，使用读锁保护
    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        let _lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        m.is_empty()
    }

    /// 清空映射，使用写锁保护
    #[inline(always)]
    pub fn clear(&self) {
        let _lock = self.lock.write();
        let m = unsafe { &mut *self.dirty.get() };
        m.clear();
    }

    /// 可变引用下的清空操作，无锁保护（调用者需确保线程安全）
    #[inline(always)]
    pub fn clear_mut(&mut self) {
        let m = unsafe { &mut *self.dirty.get() };
        m.clear();
    }

    /// 收缩容量以适应元素数量，使用写锁保护
    #[inline(always)]
    pub fn shrink_to_fit(&self) {
        let _lock = self.lock.write();
        let m = unsafe { &mut *self.dirty.get() };
        m.shrink_to_fit();
    }

    /// 可变引用下的收缩容量操作，无锁保护（调用者需确保线程安全）
    #[inline(always)]
    pub fn shrink_to_fit_mut(&mut self) {
        let m = unsafe { &mut *self.dirty.get() };
        m.shrink_to_fit();
    }

    /// 从HashMap创建SyncHashMap的便捷方法
    pub fn from(map: HashMap<K, V>) -> Self {
        Self::with_map(map)
    }

    /// 获取键对应的值引用，使用读锁保护
    ///
    /// 键可以是映射键类型的任何借用形式，但借用形式的 [`Hash`] 和 [`Eq`] 必须与键类型匹配。
    ///
    /// # Examples
    ///
    /// ```
    /// use fast_able::SyncHashMap;
    ///
    /// let map = SyncHashMap::new();
    /// map.insert(1, "a");
    /// assert_eq!(map.get(&1), Some(&"a"));
    /// assert_eq!(map.get(&2), None);
    /// ```
    #[inline]
    pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
    where
        K: Borrow<Q>,
        Q: Hash + Eq,
    {
        let _lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        m.get(k)
    }

    /// 获取键对应的可变值引用，使用写锁保护
    #[inline]
    pub fn get_mut<Q: ?Sized>(&self, k: &Q) -> Option<SyncMapRefMut<'_, K, V>>
    where
        K: Borrow<Q>,
        Q: Hash + Eq,
    {
        let _lock = self.lock.write().expect("Lock poisoned");
        let m = unsafe { &mut *self.dirty.get() };
        let value = m.get_mut(k)?;
        Some(SyncMapRefMut::<K, V> {
            _lock,
            value,
            _phantom: std::marker::PhantomData,
        })
    }

    /// 检查是否包含指定的键，使用读锁保护
    #[inline]
    pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
    where
        K: Borrow<Q>,
        Q: Hash + Eq,
    {
        let _lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        m.contains_key(k)
    }

    /// 获取可变迭代器，使用写锁保护
    pub fn iter_mut(&self) -> IterMut<'_, K, V> {
        let _lock = self.lock.write().expect("Lock poisoned");
        let m = unsafe { &mut *self.dirty.get() };
        IterMut {
            _lock,
            inner: m.iter_mut(),
        }
    }

    /// 获取只读迭代器，使用读锁保护
    pub fn iter(&self) -> MapIter<'_, K, V> {
        let _lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        m.iter()
    }

    /// 获取底层HashMap的引用（unsafe，调用者需确保无其他写操作）
    pub fn dirty_ref(&self) -> &HashMap<K, V> {
        unsafe { &*self.dirty.get() }
    }

    /// 消耗self并返回内部的HashMap
    pub fn into_inner(self) -> HashMap<K, V> {
        self.dirty.into_inner()
    }

    /// 获取键的迭代器，使用读锁保护
    #[inline]
    pub fn keys(&self) -> Keys<'_, K, V> {
        let _lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        m.keys()
    }

    /// 获取值的只读迭代器，使用读锁保护
    #[inline]
    pub fn values(&self) -> Values<'_, K, V> {
        let _lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        m.values()
    }

    /// 获取值的可变迭代器，使用写锁保护
    #[inline]
    pub fn values_mut(&self) -> ValuesMut<'_, K, V> {
        let _lock = self.lock.write();
        let m = unsafe { &mut *self.dirty.get() };
        m.values_mut()
    }

    /// 保留满足条件的元素，使用写锁保护
    #[inline]
    pub fn retain<F>(&self, f: F)
    where
        F: FnMut(&K, &mut V) -> bool,
    {
        let _lock = self.lock.write();
        let m = unsafe { &mut *self.dirty.get() };
        m.retain(f);
    }

    /// 获取映射的容量，使用读锁保护
    #[inline]
    pub fn capacity(&self) -> usize {
        let _lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        m.capacity()
    }

    /// 预留指定容量，使用写锁保护
    #[inline]
    pub fn reserve(&self, additional: usize) {
        let _lock = self.lock.write();
        let m = unsafe { &mut *self.dirty.get() };
        m.reserve(additional);
    }

    /// 尝试移除键值对，如果键存在则返回被移除的值，使用写锁保护
    #[inline]
    pub fn remove_entry(&self, k: &K) -> Option<(K, V)> {
        let _lock = self.lock.write();
        let m = unsafe { &mut *self.dirty.get() };
        m.remove_entry(k)
    }

    /// 如果键存在则返回其可变引用，否则插入新值，使用写锁保护
    #[inline]
    pub fn get_or_insert(&self, k: K, default: V) -> &mut V {
        let _lock = self.lock.write();
        let m = unsafe { &mut *self.dirty.get() };
        m.entry(k).or_insert(default)
    }

    /// 如果键存在则返回其可变引用，否则使用函数返回值插入，使用写锁保护
    #[inline]
    pub fn get_or_insert_with<F>(&self, k: K, default: F) -> &mut V
    where
        F: FnOnce() -> V,
    {
        let _lock = self.lock.write();
        let m = unsafe { &mut *self.dirty.get() };
        m.entry(k).or_insert_with(default)
    }
}

/// 可变值引用的守护者，持有写锁
pub struct SyncMapRefMut<'a, K, V> {
    /// 写锁守护者
    _lock: RwLockWriteGuard<'a, ()>,
    /// 可变值引用
    value: &'a mut V,
    /// 用于标记键类型（编译时使用）
    _phantom: std::marker::PhantomData<K>,
}

impl<'a, K, V> Deref for SyncMapRefMut<'a, K, V> {
    type Target = V;

    fn deref(&self) -> &Self::Target {
        self.value
    }
}

impl<'a, K, V> DerefMut for SyncMapRefMut<'a, K, V> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.value
    }
}

impl<'a, K, V> Debug for SyncMapRefMut<'a, K, V>
where
    V: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        self.value.fmt(f)
    }
}

impl<'a, K, V> PartialEq for SyncMapRefMut<'a, K, V>
where
    V: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        // 避免直接比较可变引用，改用引用比较
        (*self.value).eq(&*other.value)
    }
}

impl<'a, K, V> Eq for SyncMapRefMut<'a, K, V> where V: Eq {}

/// 自定义迭代器包装器（主要用于兼容性）
pub struct IterMy<'a, K, V> {
    /// 内部迭代器
    inner: MapIter<'a, K, V>,
}

impl<'a, K, V> Deref for IterMy<'a, K, V> {
    type Target = MapIter<'a, K, V>;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<'a, K, V> Iterator for IterMy<'a, K, V> {
    type Item = (&'a K, &'a V);

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }
}

/// 可变迭代器的守护者，持有写锁
pub struct IterMut<'a, K, V> {
    /// 写锁守护者
    _lock: RwLockWriteGuard<'a, ()>,
    /// 内部可变迭代器
    inner: MapIterMut<'a, K, V>,
}

impl<'a, K, V> Deref for IterMut<'a, K, V> {
    type Target = MapIterMut<'a, K, V>;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<'a, K, V> DerefMut for IterMut<'a, K, V> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

impl<'a, K, V> Iterator for IterMut<'a, K, V> {
    type Item = (&'a K, &'a mut V);

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }
}

impl<'a, K, V> IntoIterator for &'a SyncHashMap<K, V>
where
    K: Eq + Hash,
{
    type Item = (&'a K, &'a V);
    type IntoIter = MapIter<'a, K, V>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<K, V> IntoIterator for SyncHashMap<K, V>
where
    K: Eq + Hash,
{
    type Item = (K, V);
    type IntoIter = MapIntoIter<K, V>;

    fn into_iter(self) -> Self::IntoIter {
        self.into_inner().into_iter()
    }
}

impl<K, V> From<HashMap<K, V>> for SyncHashMap<K, V>
where
    K: Eq + Hash,
{
    fn from(map: HashMap<K, V>) -> Self {
        Self::from(map)
    }
}

impl<K, V> Serialize for SyncHashMap<K, V>
where
    K: Eq + Hash + Serialize,
    V: Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let _lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        m.serialize(serializer)
    }
}

impl<'de, K, V> Deserialize<'de> for SyncHashMap<K, V>
where
    K: Eq + Hash + Deserialize<'de>,
    V: Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let m = HashMap::deserialize(deserializer)?;
        Ok(Self::from(m))
    }
}

impl<K, V> Debug for SyncHashMap<K, V>
where
    K: Eq + Hash + Debug,
    V: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let _lock = self.lock.read();
        let m = unsafe { &*self.dirty.get() };
        m.fmt(f)
    }
}

impl<K, V> Clone for SyncHashMap<K, V>
where
    K: Clone + Eq + Hash,
    V: Clone,
{
    fn clone(&self) -> Self {
        let _lock = self.lock.read();
        let c = unsafe { &*self.dirty.get() }.clone();
        SyncHashMap::from(c)
    }
}

impl<K, V> Default for SyncHashMap<K, V>
where
    K: Eq + Hash,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<K, V> PartialEq for SyncHashMap<K, V>
where
    K: Eq + Hash,
    V: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        let _lock_self = self.lock.read();
        let _lock_other = other.lock.read();
        let self_map = unsafe { &*self.dirty.get() };
        let other_map = unsafe { &*other.dirty.get() };
        self_map.eq(other_map)
    }
}

impl<K, V> Eq for SyncHashMap<K, V>
where
    K: Eq + Hash,
    V: Eq,
{
}

/// 分桶哈希映射模块，提供更高并发的哈希映射实现
pub mod buckets {
    use super::{SyncHashMap, SyncMapRefMut};
    use std::hash::{Hash, Hasher};

    /// 分桶哈希映射，将数据分散到多个子映射中以提高并发性能
    #[derive(Debug, Clone)]
    pub struct SyncHashMapB<K, V>
    where
        K: Eq + Hash,
    {
        /// 内部的子映射数组
        inner: Vec<SyncHashMap<K, V>>,
        /// 分桶数量
        len: usize,
    }

    impl<K, V> SyncHashMapB<K, V>
    where
        K: Eq + Hash,
    {
        /// 创建新的分桶哈希映射
        ///
        /// # Arguments
        /// * `bucket_count` - 分桶数量，如果为None则默认为10
        ///
        /// # Examples
        /// ```
        /// use fast_able::map_hash::buckets::SyncHashMapB;
        ///
        /// let map = SyncHashMapB::new(None);
        /// map.insert(1, "a");
        /// map.insert(2, "b");
        /// assert_eq!(map.get(&1), Some(&"a"));
        /// assert_eq!(map.get(&2), Some(&"b"));
        /// assert_eq!(map.get(&3), None);
        /// ```
        pub fn new(bucket_count: Option<usize>) -> Self {
            let count = bucket_count.unwrap_or(10);
            let mut arr = Vec::with_capacity(count);
            for _ in 0..count {
                arr.push(SyncHashMap::new());
            }
            Self {
                inner: arr,
                len: count,
            }
        }

        /// 将键转换为桶索引
        fn key_to_bucket_index(&self, k: &K) -> usize {
            let mut hasher = std::collections::hash_map::DefaultHasher::new();
            k.hash(&mut hasher);
            let hash = hasher.finish();
            (hash % self.len as u64) as usize
        }

        /// 插入键值对
        #[inline]
        pub fn insert(&self, k: K, v: V) -> Option<V> {
            let index = self.key_to_bucket_index(&k);
            self.inner[index].insert(k, v)
        }

        /// 可变引用下的插入操作
        #[inline]
        pub fn insert_mut(&mut self, k: K, v: V) -> Option<V> {
            let index = self.key_to_bucket_index(&k);
            self.inner[index].insert_mut(k, v)
        }

        /// 移除键值对
        #[inline]
        pub fn remove(&self, k: &K) -> Option<V> {
            let index = self.key_to_bucket_index(k);
            self.inner[index].remove(k)
        }

        /// 检查是否为空
        #[inline]
        pub fn is_empty(&self) -> bool {
            self.inner.iter().all(|bucket| bucket.is_empty())
        }

        /// 获取总长度
        #[inline]
        pub fn len(&self) -> usize {
            self.inner.iter().map(|bucket| bucket.len()).sum()
        }

        /// 清空所有桶
        #[inline]
        pub fn clear(&self) {
            self.inner.iter().for_each(|bucket| bucket.clear());
        }

        /// 获取键对应的值引用
        #[inline]
        pub fn get(&self, k: &K) -> Option<&V> {
            let index = self.key_to_bucket_index(k);
            self.inner[index].get(k)
        }

        /// 获取键对应的可变值引用
        #[inline]
        pub fn get_mut(&self, k: &K) -> Option<SyncMapRefMut<'_, K, V>> {
            let index = self.key_to_bucket_index(k);
            self.inner[index].get_mut(k)
        }

        /// 获取桶数量
        #[inline]
        pub fn bucket_count(&self) -> usize {
            self.len
        }

        /// 获取所有键的迭代器
        #[inline]
        pub fn keys(&self) -> impl Iterator<Item = &K> {
            self.inner.iter().flat_map(|bucket| bucket.keys())
        }

        /// 获取所有值的只读迭代器
        #[inline]
        pub fn values(&self) -> impl Iterator<Item = &V> {
            self.inner.iter().flat_map(|bucket| bucket.values())
        }

        /// 获取所有值的可变迭代器（注意：这是一个简化实现，返回值的锁可能不够严格）
        #[inline]
        pub fn values_mut(&self) -> impl Iterator<Item = &mut V> {
            self.inner.iter().flat_map(|bucket| bucket.values_mut())
        }
    }

    impl<K, V> Default for SyncHashMapB<K, V>
    where
        K: Eq + Hash,
    {
        fn default() -> Self {
            Self::new(None)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use std::sync::Arc;
    use std::thread;

    #[test]
    fn test_sync_hash_map_new() {
        let map: SyncHashMap<i32, String> = SyncHashMap::new();
        assert_eq!(map.len(), 0);
        assert!(map.is_empty());
    }

    #[test]
    fn test_sync_hash_map_with_capacity() {
        let map = SyncHashMap::<i32, String>::with_capacity(100);
        assert!(map.capacity() >= 100);
    }

    #[test]
    fn test_sync_hash_map_with_map() {
        let mut original = HashMap::new();
        original.insert(1, "one".to_string());
        original.insert(2, "two".to_string());

        let map = SyncHashMap::with_map(original);
        assert_eq!(map.len(), 2);
        assert_eq!(map.get(&1), Some(&"one".to_string()));
        assert_eq!(map.get(&2), Some(&"two".to_string()));
    }

    #[test]
    fn test_sync_hash_map_insert_and_get() {
        let map = SyncHashMap::new();

        // 测试插入和获取
        assert_eq!(map.insert(1, "one".to_string()), None);
        assert_eq!(map.insert(2, "two".to_string()), None);
        assert_eq!(map.len(), 2);

        assert_eq!(map.get(&1), Some(&"one".to_string()));
        assert_eq!(map.get(&2), Some(&"two".to_string()));
        assert_eq!(map.get(&3), None);
    }

    #[test]
    fn test_sync_hash_map_insert_replace() {
        let map = SyncHashMap::new();

        assert_eq!(map.insert(1, "one".to_string()), None);
        assert_eq!(map.insert(1, "updated".to_string()), Some("one".to_string()));
        assert_eq!(map.get(&1), Some(&"updated".to_string()));
    }

    #[test]
    fn test_sync_hash_map_remove() {
        let map = SyncHashMap::new();

        map.insert(1, "one".to_string());
        map.insert(2, "two".to_string());

        assert_eq!(map.remove(&1), Some("one".to_string()));
        assert_eq!(map.remove(&1), None);
        assert_eq!(map.len(), 1);
        assert_eq!(map.get(&1), None);
        assert_eq!(map.get(&2), Some(&"two".to_string()));
    }

    #[test]
    fn test_sync_hash_map_contains_key() {
        let map = SyncHashMap::new();

        map.insert(1, "one".to_string());

        assert!(map.contains_key(&1));
        assert!(!map.contains_key(&2));
    }

    #[test]
    fn test_sync_hash_map_clear() {
        let map = SyncHashMap::new();

        map.insert(1, "one".to_string());
        map.insert(2, "two".to_string());

        assert_eq!(map.len(), 2);
        map.clear();
        assert_eq!(map.len(), 0);
        assert!(map.is_empty());
    }

    #[test]
    fn test_sync_hash_map_capacity_operations() {
        let map = SyncHashMap::new();

        assert_eq!(map.capacity(), 0);
        map.reserve(100);
        assert!(map.capacity() >= 100);

        map.insert(1, "one".to_string());
        map.insert(2, "two".to_string());

        let old_capacity = map.capacity();
        map.shrink_to_fit();
        assert!(map.capacity() <= old_capacity);
    }

    #[test]
    fn test_sync_hash_map_retain() {
        let map = SyncHashMap::new();

        map.insert(1, "one".to_string());
        map.insert(2, "two".to_string());
        map.insert(3, "three".to_string());

        map.retain(|&k, _| k % 2 == 1);

        assert_eq!(map.len(), 2);
        assert!(map.contains_key(&1));
        assert!(!map.contains_key(&2));
        assert!(map.contains_key(&3));
    }

    #[test]
    fn test_sync_hash_map_get_or_insert() {
        let map = SyncHashMap::new();

        // 键不存在时插入
        let value = map.get_or_insert(1, "default".to_string());
        assert_eq!(value, "default");
        assert_eq!(map.len(), 1);

        // 键存在时返回现有值
        let value = map.get_or_insert(1, "new_default".to_string());
        assert_eq!(value, "default");
        assert_eq!(map.len(), 1);
    }

    #[test]
    fn test_sync_hash_map_get_or_insert_with() {
        let map = SyncHashMap::new();

        let value = map.get_or_insert_with(1, || "computed".to_string());
        assert_eq!(value, "computed");
        assert_eq!(map.len(), 1);

        let value = map.get_or_insert_with(1, || "new_computed".to_string());
        assert_eq!(value, "computed");
    }

    #[test]
    fn test_sync_hash_map_remove_entry() {
        let map = SyncHashMap::new();

        map.insert(1, "one".to_string());
        map.insert(2, "two".to_string());

        let removed = map.remove_entry(&1);
        assert_eq!(removed, Some((1, "one".to_string())));
        assert_eq!(map.len(), 1);
        assert!(!map.contains_key(&1));
    }

    #[test]
    fn test_sync_hash_map_iterators() {
        let map = SyncHashMap::new();

        map.insert(1, "one".to_string());
        map.insert(2, "two".to_string());
        map.insert(3, "three".to_string());

        // 测试 keys 迭代器
        let keys: Vec<_> = map.keys().collect();
        assert!(keys.contains(&&1));
        assert!(keys.contains(&&2));
        assert!(keys.contains(&&3));

        // 测试 values 迭代器
        let values: Vec<_> = map.values().collect();
        assert!(values.contains(&&"one".to_string()));
        assert!(values.contains(&&"two".to_string()));
        assert!(values.contains(&&"three".to_string()));

        // 测试 iter 迭代器
        let mut count = 0;
        for (k, v) in map.iter() {
            count += 1;
            assert!(map.contains_key(k));
            assert_eq!(map.get(k), Some(v));
        }
        assert_eq!(count, 3);
    }

    #[test]
    fn test_sync_hash_map_iter_mut() {
        let map = SyncHashMap::new();

        map.insert(1, "one".to_string());
        map.insert(2, "two".to_string());

        for (k, v) in map.iter_mut() {
            if *k == 1 {
                *v = "modified".to_string();
            }
        }

        assert_eq!(map.get(&1), Some(&"modified".to_string()));
        assert_eq!(map.get(&2), Some(&"two".to_string()));
    }

    #[test]
    fn test_sync_hash_map_values_mut() {
        let map = SyncHashMap::new();

        map.insert(1, "one".to_string());
        map.insert(2, "two".to_string());

        for v in map.values_mut() {
            if v == "one" {
                *v = "modified".to_string();
            }
        }

        assert_eq!(map.get(&1), Some(&"modified".to_string()));
        assert_eq!(map.get(&2), Some(&"two".to_string()));
    }

    #[test]
    fn test_sync_hash_map_index() {
        let map = SyncHashMap::new();
        map.insert(1, "one".to_string());

        // 测试索引访问
        assert_eq!(map[&1], "one");
    }

    #[test]
    fn test_sync_hash_map_clone() {
        let map1 = SyncHashMap::new();
        map1.insert(1, "one".to_string());
        map1.insert(2, "two".to_string());

        let map2 = map1.clone();

        assert_eq!(map1.len(), map2.len());
        assert_eq!(map1.get(&1), map2.get(&1));
        assert_eq!(map1.get(&2), map2.get(&2));

        // 修改原映射不影响克隆
        map1.insert(3, "three".to_string());
        assert!(!map2.contains_key(&3));
    }

    #[test]
    fn test_sync_hash_map_partial_eq() {
        let map1 = SyncHashMap::new();
        map1.insert(1, "one".to_string());
        map1.insert(2, "two".to_string());

        let map2 = SyncHashMap::new();
        map2.insert(1, "one".to_string());
        map2.insert(2, "two".to_string());

        let map3 = SyncHashMap::new();
        map3.insert(1, "different".to_string());

        assert_eq!(map1, map2);
        assert_ne!(map1, map3);
    }

    #[test]
    fn test_sync_hash_map_debug() {
        let map = SyncHashMap::new();
        map.insert(1, "one".to_string());

        let debug_str = format!("{:?}", map);
        assert!(debug_str.contains("1"));
        assert!(debug_str.contains("one"));
    }

    #[test]
    fn test_sync_hash_map_serialization() {
        let map = SyncHashMap::new();
        map.insert(1, "one".to_string());
        map.insert(2, "two".to_string());

        // 测试序列化
        let serialized = serde_json::to_string(&map).unwrap();
        assert!(serialized.contains("1"));
        assert!(serialized.contains("one"));
        assert!(serialized.contains("2"));
        assert!(serialized.contains("two"));

        // 测试反序列化
        let deserialized: SyncHashMap<i32, String> = serde_json::from_str(&serialized).unwrap();
        assert_eq!(deserialized.len(), 2);
        assert_eq!(deserialized.get(&1), Some(&"one".to_string()));
        assert_eq!(deserialized.get(&2), Some(&"two".to_string()));
    }

    #[test]
    fn test_sync_hash_map_from_hashmap() {
        let mut original = HashMap::new();
        original.insert(1, "one".to_string());
        original.insert(2, "two".to_string());

        let map = SyncHashMap::from(original);

        assert_eq!(map.len(), 2);
        assert_eq!(map.get(&1), Some(&"one".to_string()));
        assert_eq!(map.get(&2), Some(&"two".to_string()));
    }

    #[test]
    fn test_sync_hash_map_into_iterator() {
        let map = SyncHashMap::new();
        map.insert(1, "one".to_string());
        map.insert(2, "two".to_string());

        // 测试 IntoIterator for &SyncHashMap
        let mut count = 0;
        for (k, v) in &map {
            count += 1;
            assert!(map.contains_key(k));
            assert_eq!(map.get(k), Some(v));
        }
        assert_eq!(count, 2);

        // 测试 IntoIterator for SyncHashMap
        let owned_pairs: Vec<_> = map.into_iter().collect();
        assert_eq!(owned_pairs.len(), 2);
    }

    #[test]
    fn test_sync_hash_map_default() {
        let map: SyncHashMap<i32, String> = Default::default();
        assert_eq!(map.len(), 0);
        assert!(map.is_empty());
    }

    #[test]
    fn test_sync_hash_map_arc() {
        let map = SyncHashMap::new_arc();
        map.insert(1, "one".to_string());

        assert_eq!(map.get(&1), Some(&"one".to_string()));

        let map2 = Arc::clone(&map);
        map2.insert(2, "two".to_string());

        assert_eq!(map.get(&2), Some(&"two".to_string()));
    }

    #[test]
    fn test_sync_hash_map_get_mut() {
        let map = SyncHashMap::new();
        map.insert(1, "one".to_string());

        {
            let mut value = map.get_mut(&1).unwrap();
            *value = "modified".to_string();
        }

        assert_eq!(map.get(&1), Some(&"modified".to_string()));
    }

    #[test]
    fn test_sync_hash_map_concurrent_access() {
        let map = Arc::new(SyncHashMap::new());

        // 并发写入测试
        let handles: Vec<_> = (0..10).map(|i| {
            let map = Arc::clone(&map);
            thread::spawn(move || {
                map.insert(i, format!("value_{}", i));
            })
        }).collect();

        for handle in handles {
            handle.join().unwrap();
        }

        // 验证所有值都被插入
        assert_eq!(map.len(), 10);
        for i in 0..10 {
            assert_eq!(map.get(&i), Some(&format!("value_{}", i)));
        }

        // 并发读取测试
        let map_read = Arc::clone(&map);
        let handles: Vec<_> = (0..10).map(|i| {
            let map = Arc::clone(&map_read);
            thread::spawn(move || {
                let value = map.get(&i);
                assert_eq!(value, Some(&format!("value_{}", i)));
            })
        }).collect();

        for handle in handles {
            handle.join().unwrap();
        }
    }

    #[test]
    fn test_sync_hash_map_dirty_ref() {
        let map = SyncHashMap::new();
        map.insert(1, "one".to_string());

        let dirty = map.dirty_ref();
        assert_eq!(dirty.len(), 1);
        assert_eq!(dirty.get(&1), Some(&"one".to_string()));
    }

    #[test]
    fn test_sync_hash_map_into_inner() {
        let map = SyncHashMap::new();
        map.insert(1, "one".to_string());
        map.insert(2, "two".to_string());

        let inner = map.into_inner();
        assert_eq!(inner.len(), 2);
        assert_eq!(inner.get(&1), Some(&"one".to_string()));
        assert_eq!(inner.get(&2), Some(&"two".to_string()));
    }

    #[test]
    fn test_sync_hash_map_guard_debug() {
        let map = SyncHashMap::new();
        map.insert(1, "test".to_string());

        let guard = map.get(&1).unwrap();
        let debug_str = format!("{:?}", guard);
        assert!(debug_str.contains("test"));
    }

    #[test]
    fn test_sync_hash_map_guard_partial_eq() {
        let map = SyncHashMap::new();
        map.insert(1, "value".to_string());

        let guard1 = map.get(&1).unwrap();
        let guard2 = map.get(&1).unwrap();

        assert_eq!(guard1, guard2);
    }

    // 分桶映射测试
    mod buckets_tests {
        use super::*;

        #[test]
        fn test_sync_hash_map_buckets_new() {
            let map = buckets::SyncHashMapB::<i32, String>::new(None);
            assert_eq!(map.len(), 0);
            assert!(map.is_empty());
            assert_eq!(map.bucket_count(), 10); // 默认桶数量
        }

        #[test]
        fn test_sync_hash_map_buckets_with_custom_size() {
            let map = buckets::SyncHashMapB::<i32, String>::new(Some(5));
            assert_eq!(map.bucket_count(), 5);
        }

        #[test]
        fn test_sync_hash_map_buckets_insert_and_get() {
            let map = buckets::SyncHashMapB::new(Some(3));

            assert_eq!(map.insert(1, "one".to_string()), None);
            assert_eq!(map.insert(2, "two".to_string()), None);
            assert_eq!(map.len(), 2);

            assert_eq!(map.get(&1), Some(&"one".to_string()));
            assert_eq!(map.get(&2), Some(&"two".to_string()));
            assert_eq!(map.get(&3), None);
        }

        #[test]
        fn test_sync_hash_map_buckets_remove() {
            let map = buckets::SyncHashMapB::new(Some(3));

            map.insert(1, "one".to_string());
            map.insert(2, "two".to_string());

            assert_eq!(map.remove(&1), Some("one".to_string()));
            assert_eq!(map.len(), 1);
            assert_eq!(map.get(&1), None);
            assert_eq!(map.get(&2), Some(&"two".to_string()));
        }

        #[test]
        fn test_sync_hash_map_buckets_clear() {
            let map = buckets::SyncHashMapB::new(Some(3));

            map.insert(1, "one".to_string());
            map.insert(2, "two".to_string());

            assert_eq!(map.len(), 2);
            map.clear();
            assert_eq!(map.len(), 0);
            assert!(map.is_empty());
        }

        #[test]
        fn test_sync_hash_map_buckets_iterators() {
            let map = buckets::SyncHashMapB::new(Some(3));

            map.insert(1, "one".to_string());
            map.insert(2, "two".to_string());
            map.insert(3, "three".to_string());

            // 测试 keys 迭代器
            let keys: Vec<_> = map.keys().collect();
            assert!(keys.contains(&&1));
            assert!(keys.contains(&&2));
            assert!(keys.contains(&&3));

            // 测试 values 迭代器
            let values: Vec<_> = map.values().collect();
            assert!(values.contains(&&"one".to_string()));
            assert!(values.contains(&&"two".to_string()));
            assert!(values.contains(&&"three".to_string()));

            // 测试 values_mut 迭代器
            for v in map.values_mut() {
                if v == "one" {
                    *v = "modified".to_string();
                }
            }

            assert_eq!(map.get(&1), Some(&"modified".to_string()));
        }

        #[test]
        fn test_sync_hash_map_buckets_default() {
            let map: buckets::SyncHashMapB<i32, String> = Default::default();
            assert_eq!(map.len(), 0);
            assert!(map.is_empty());
            assert_eq!(map.bucket_count(), 10);
        }

        #[test]
        fn test_sync_hash_map_buckets_debug() {
            let map = buckets::SyncHashMapB::new(Some(2));
            map.insert(1, "one".to_string());

            let debug_str = format!("{:?}", map);
            assert!(debug_str.contains("1"));
            assert!(debug_str.contains("one"));
        }
    }

    #[test]
    fn test_sync_hash_map_comprehensive() {
        let map = SyncHashMap::new();

        // 测试各种操作的组合
        map.insert("key1", 42);
        map.insert("key2", 24);

        assert_eq!(map.len(), 2);
        assert!(!map.is_empty());

        // 测试修改操作
        *map.get_mut("key1").unwrap() = 100;
        assert_eq!(map.get(&"key1"), Some(&100));

        // 测试条件保留
        map.insert("key3", 50);
        map.retain(|_, &mut v| v > 30);

        assert_eq!(map.len(), 2);
        assert_eq!(map.get(&"key1"), Some(&100));
        assert_eq!(map.get(&"key2"), None);
        assert_eq!(map.get(&"key3"), Some(&50));

        // 测试克隆和比较
        let map2 = map.clone();
        assert_eq!(map, map2);

        // 测试迭代
        let mut sum = 0;
        for (_, v) in map.iter() {
            sum += v;
        }
        assert_eq!(sum, 150);

        // 测试清空
        map.clear();
        assert_eq!(map.len(), 0);
        assert!(map.is_empty());
    }
}
